from django.contrib import admin
from django.utils.html import format_html

from .models import User, Order, Category, Product, Config, ProductCount, Address

# Register your models here.

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('email', 'nickname', 'avatar', 'gender', 'balance', 'created_time')
    list_filter = ('gender', 'created_time')
    search_fields = ('email', 'nickname')
    ordering = ('-created_time',)
    readonly_fields = ('created_time',)

    def avatar_preview(self, obj):
        if obj.pic_url:
            return format_html('<img src="{}" width="100" />', obj.avatar)
        return "No Image"

    avatar_preview.short_description = '头像预览'
    avatar_preview.allow_tags = True

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('order_id', 'user', 'payment', 'status', 'created_time', 'payment_time', 'consign_time', 'end_time')
    list_filter = ('status', 'created_time', 'payment_time', 'consign_time', 'end_time')
    search_fields = ('order_id', 'user__email', 'user__nickname')
    date_hierarchy = 'created_time'
    ordering = ('-id',)
    readonly_fields = ('created_time', 'payment_time', 'consign_time', 'end_time')

    fieldsets = (
        (None, {
            'fields': ('order_id', 'user', 'payment', 'status', 'express_name', 'express_number', 'products')
        }),
        ('时间信息', {
            'fields': ('created_time', 'payment_time', 'consign_time', 'end_time')
        }),
        ('用户信息', {
            'fields': ('name', 'phone', 'dz')
        }),
    )

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'brief', 'price', 'category', 'pic_preview')
    list_filter = ('category',)
    search_fields = ('name', 'brief')

    # 图片预览功能
    def pic_preview(self, obj):
        if obj.pic_url:
            return format_html('<img src="{}" width="100" />', obj.pic_url.url)
        return "No Image"

    pic_preview.short_description = '图片预览'


@admin.register(Config)
class ConfigAdmin(admin.ModelAdmin):
    list_display = ('product', 'name', 'price', 'default', 'get_choices_display')
    list_filter = ('product',)
    search_fields = ('name', 'default')

    # 显示选项列表的 JSON 格式
    def get_choices_display(self, obj):
        return ", ".join(obj.choices)

    get_choices_display.short_description = '选项列表'

@admin.register(ProductCount)
class ProductCountAdmin(admin.ModelAdmin):
    list_display = ('product', 'price', 'count')
    list_filter = ('product',)
    search_fields = ('product__name',)

@admin.register(Address)
class AddressAdmin(admin.ModelAdmin):
    list_display = ('user', 'name', 'phone', 'dz')
    list_filter = ('user',)
    search_fields = ('user__email', 'user__nickname', 'name', 'phone')